<template>
  <div class="app">
    <div class="search-bar">
      <el-form :model="searchData" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="公司名称" style="margin-bottom: 5px;">
              <el-input v-model="searchData.registerName" size="medium" clearable class="select" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="注册类型" style="margin-bottom: 5px;">
              <el-select v-model="searchData.registerType" size="medium" clearable class="select">
                <el-option
                  v-for="item in registerTypeOptions"
                  :key="item.index"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div style="margin-top: 3px;">
              <el-button icon="el-icon-search" type="primary" size="small" @click="legalHandleSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" size="small" @click="legalHandleClear">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div v-show="canUsed" class="button-bar">
      <el-button icon="el-icon-plus" type="primary" size="small" @click="handleAdd">新增</el-button>
      <el-button icon="el-icon-delete" type="danger" size="small" @click="handleDel">删除</el-button>
    </div>
    <div ref="ref" :class="canUsed?'table-box':'table-box2'">
      <tableComponent
        class="table"
        :height="height"
        :data="legalTableData || []"
        :columns="legalTableColumns"
        @change="legalTablePage"
        :table-option="tableOption"
        :page-option="pageOption"
        :total="total"
        @selectionChange="handleSelectChange"
      >
        <template slot-scope="scope">
          <div class="options">
            <el-button type="text" @click="legalSeeItem(scope.scope.row)">查看</el-button>
            <el-button v-show="canUsed" type="text" @click="legalEditItem(scope.scope.row)">修改</el-button>
          </div>
        </template>
      </tableComponent>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="100px" style="padding: 0 30px;" label-position="left" :disabled="disabled">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="注册中文名" prop="companyChiName">
              <el-input class="input" v-model="form.companyChiName" size="medium"></el-input>
            </el-form-item>
            <el-form-item label="注册地区" prop="location">
              <el-cascader
                v-model="form.location"
                :options="options"
                @change="handleChange"
                :props="prop"
                size="medium"
                :disabled="disabled"
                class="select"
                filterable
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="注册类型" prop="registerType">
              <el-select v-model="form.registerType" class="select" size="medium">
                <el-option
                  v-for="item in registerTypeOptions"
                  :key="item.value"
                  :label="item.value"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册英文名" prop="companyEngName">
              <el-input class="input" v-model="form.companyEngName" size="medium"></el-input>
            </el-form-item>
            <el-form-item label="国有出资情形" prop="stateEnterpreiseCapi">
              <el-select v-model="form.stateEnterpreiseCapi" class="select" size="medium">
                <el-option
                  v-for="item in stateEnterpreiseCapi"
                  :key="item.value"
                  :label="item.value"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="新增日期" prop="registerId">
              <el-date-picker
                v-model="form.addDate"
                type="date"
                placeholder="选择日期"
                format="yyyy 年 MM 月 dd 日"
                size="medium"
                class="select"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancle">取 消</el-button>
        <el-button v-show="!disabled" type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableComponent from '@/components/Table/table'
import { legalTableColumns } from "./index.js"
import { getLegalData, delLegalData, addLegalData, editLegalData, seeLegalData, queryLegalRegisterType } from '@/api/modules/legalAndNatural.js'
import { allArea, stateEnterpriseCapi } from '@/api/modules/propertyRight.js'
export default {
  components: {
    tableComponent,
  },
  data() {
    return {
      searchData: {
        registerName: '',
        registerType: '',
        page: {
          pageNum: 1,
          pageSize: 10
        }
      },
      height: null,
      legalTableData: [],
      legalTableColumns,
      tableOption: {
        isShowOperate: true,
        isMultiSelect: true,
        operateWidth: '120px'
      },
      pageOption: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      ids: [], // 存储表格数据ID用于删除或批量删除
      // dialogParams==============================
      dialogVisible: false,
      title: '',
      form: {
        companyCode: '',
        companyChiName: '',
        companyEngName: '',
        registerId: '',
        location: [],
        stateEnterpreiseCapi: '',
        registerType: '',
      },
      disabled: false,
      registerTypeOptions: [],
      businessOption: [],
      stateEnterpreiseCapi: [],
      options: [],
      prop: {
        label: 'name',
        value: 'code',
        children: 'child'
      },
      canUsed: true // 判断权限
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.height = this.$refs.ref.offsetHeight
    })
    window.onresize = () => {
      this.height = this.$refs.ref.offsetHeight
    }
    const query = this.$route.query.name
    if (query != '') {
      this.searchData.registerName = query
      this.initData(this.searchData)
    } else {
      const key = this.$store.state.key.resourceCode
      if (key === '0') {
        this.canUsed = false
      } else {
        this.canUsed = true
      }
      this.initData(this.searchData)
    }
  },
  destroyed(){
    window.onresize = null
  },
  methods: {
    initData(params) {
      getLegalData(params).then(res => {
        this.legalTableData = res.data.body.list
        this.total = res.data.body.total
      })
      allArea().then(res => {
        if (res.data.code === '0') {
          this.options = this.getTreeData(res.data.body)
        }
      })
      queryLegalRegisterType().then(res => {
        if (res.data.code === '0') {
          this.registerTypeOptions = res.data.body
        }
      })
      stateEnterpriseCapi().then(res => {
        this.stateEnterpreiseCapi = res.data.body
      })
    },
    // 法人查询
    legalHandleSearch() {
      this.initData()
    },
    // 法人重置
    legalHandleClear() {
      this.searchData = {}
    },
    // 法人表格分页
    legalTablePage(page) {
      this.searchData.page = page
      this.initData()
    },
    // 法人查看
    legalSeeItem(row) {
      this.dialogVisible = true
      this.title = '查看他方企业信息'
      this.disabled = true
      const params = {
        companyCode: row.companyCode
      }
      seeLegalData(params).then(res => {
        if (res.data.code === '0') {
          this.form = res.data.body
        }
      })
    },
    // 法人修改
    legalEditItem(row) {
      this.dialogVisible = true
      this.title = '修改他方企业信息'
      this.disabled = false
      const params = {
        companyCode: row.companyCode
      }
      seeLegalData(params).then(res => {
        if (res.data.code === '0') {
          this.form = res.data.body
        }
      })
    },
    // 法人新增
    handleAdd() {
      this.dialogVisible = true
      this.title = '新增他方企业信息'
      this.disabled = false
    },
    // 法人表格复选框被选中
    handleSelectChange(row) {
      const data = row
      this.ids = []
      data.forEach(item => {
        this.ids.push(item.companyCode)
      })
      console.log(this.ids)
    },
    // 法人表格删除
    handleDel() {
      if (!this.ids.length) {
        this.$message({
          type: 'error',
          message: '请选择要删除的数据'
        })
      } else {
        this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delLegalData(this.ids).then(res => {
            if (res.data.code === '0') {
              this.$message.success('删除成功')
              this.initData()
            } else {
              this.$message.error(res.data.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    // dialogFunction==================
    getTreeData(data){
      // 循环遍历json数据
      for(let i=0;i<data.length;i++){
        if(data[i].child.length<1){
          // children若为空数组，则将children设为undefined
          data[i].child = undefined
        }else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].child)
        }
      }
      return data
    },
    // 选择所在地区
    handleChange(val) {
      this.form.location = val
    },
    handleSubmit() {
      if (this.form.companyChiName === ''&&this.form.companyEngName === '') {
        this.$message.error('注册中文或注册英文名必须录入一个')
      } else if (this.form.companyChiName === null&&this.form.companyEngName === null) {
        this.$message.error('注册中文或注册英文名必须录入一个')
      } else if (this.form.companyChiName === ''&&this.form.companyEngName === null) {
        this.$message.error('注册中文或注册英文名必须录入一个')
      } else if (this.form.companyChiName === null&&this.form.companyEngName === '') {
        this.$message.error('注册中文或注册英文名必须录入一个')
      } else {
        if (this.title === '新增他方企业信息') {
          this.$refs['form'].validate((valid) => {
            if (valid) {
              addLegalData(this.form).then(res => {
                if (res.data.code === '0') {
                  this.$message.success('新增成功')
                  this.handleCancle()
                  this.initData()
                } else {
                  this.$message.error(res.data.message)
                }
              })
            } else {
              return false
            }
          })
        } else if (this.title === '修改他方企业信息') {
          this.$refs['form'].validate((valid) => {
            if (valid) {
              editLegalData(this.form).then(res => {
                if (res.data.code === '0') {
                  this.$message.success('修改成功')
                  this.handleCancle()
                  this.initData()
                } else {
                  this.$message.error(res.data.message)
                }
              })
            } else {
              return false
            }
          })
        }
      }
    },
    // 弹窗关闭前的回调
    handleClose() {
      this.resetForm('form')
      this.dialogVisible = false
    },
    handleCancle() {
      this.resetForm('form')
      this.dialogVisible = false
    },
     // 清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
  .app {
    width: 100%;
    .search-bar {
      width: 100%;
      background-color: #ffffff;
      padding: 10px 0px;
      margin-bottom: 10px;
    }
    .button-bar {
      width: calc(100% - 40px);
      padding: 10px 20px 10px 20px;
      background-color: #ffffff;
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 260px);
      .table {
        height: 100%;
      }
    }
    .table-box2 {
      width: 100%;
      height: calc(100vh - 210px);
      .table {
        height: 100%;
      }
    }
    .select {
      width: 100%;
    }
    .input {
      width: 100%;
    }
  }
</style>
<style>
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-input.is-disabled .el-input__inner {
    background-color: rgb(228,231,237,0.15);
    border-color: #E4E7ED;
    color: #606266;
  }
  .el-textarea.is-disabled .el-textarea__inner {
    background-color: rgb(228,231,237,0.15);
    border-color: #E4E7ED;
    color: #606266;
  }
  .table-row th {
   text-align: center;
  }
</style>